/*

   **********************************************************************
   *                                                                    *
   * This file contains the code for an image object for a content-     *
   * based image retrieval application that "summarizes" an image and   *
   * sends the resulting image "signature" to a server for              *
   * classification. The server returns the classification result in    *
   * the form of a Web page containing example images of the input      *
   * image's category.                                                  *
   *                                                                    *
   * The image class defined here is rather specific to this particular *
   * application and is not really designed for broad reuse (just yet). *
   *                                                                    *
   **********************************************************************
*/

/*
   **********************************************************************
   *                                                                    *
   * Gist   -- content-based image retrieval application for the gPhone *
   *                                                                    *
   * Copyright (C) 2011 Yong Zeng                                       *
   *                                                                    *
   * This file is part of Gist.                                       *
   *                                                                    *
   * Gist is free software; you can redistribute it and/or modify it  *
   * under the terms of the GNU General Public License as published by  *
   * the Free Software Foundation; either version 2 of the License, or  *
   * (at your option) any later version.                                *
   *                                                                    *
   * Gist is distributed in the hope that it will be useful, but      *
   * WITHOUT ANY WARRANTY; without even the implied warranty of         *
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   *
   * General Public License for more details.                           *
   *                                                                    *
   * You should have received a copy of the GNU General Public License  *
   * along with Goggle; if not, write to the Free Software Foundation,  *
   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.       *
   *                                                                    *
   **********************************************************************
*/
//----------------------- PACKAGE SPECIFICATION -------------------------
package vision.gistcomputing;
//------------------------------ IMPORTS --------------------------------
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.*;
import android.util.Log;
//----------------- THE CLASSIFICATION RESULTS SCREEN -------------------
public class HttpFileUploader implements Runnable {

	URL connectURL;
	String responseString;
	String fileName;
	byte[] dataToServer;
	InputStream fileInputStream = null;
	String resultUrl = "";
	HttpFileUploader(String urlString, String fileName) {
		try {
			connectURL = new URL(urlString);
		} catch (Exception ex) {
			Log.i("URL FORMATION", "MALFORMATED URL");
		}
		// this.params = params + "=";
		this.fileName = fileName;
		Log.e("HFU", "HFU created");
		Log.e("HFU", "File name :"+fileName);
		Log.e("HFU", "URL :"+urlString);
	}
	void doStart(InputStream stream) {
		fileInputStream = stream;
		thirdTry();
	}	
	void thirdTry() {
		String exsistingFileName = fileName;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		
		//The boundary value is probably of the form --------------------------------1878979834, 
		//where the digits are randomly generated. This boundary is a MIME boundary; 
		//it's guaranteed not to appear anywhere in the data except between 
		//the multiple parts of the data.
		
		String boundary = "--AaB03x"; 
		String Tag = "post";
		try {
			// ------------------ CLIENT REQUEST

			Log.e(Tag, "Start connection");
			// Open a HTTP connection to the URL

			HttpURLConnection conn = (HttpURLConnection) connectURL
					.openConnection();

			// Allow Inputs
			conn.setDoInput(true);

			// Allow Outputs
			conn.setDoOutput(true);

			// Don't use a cached copy.
			conn.setUseCaches(false);

			// Use a post method.
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Connection", "Keep-Alive");

			conn.setRequestProperty("Content-Type",
					"multipart/form-data,boundary=" + boundary);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			doDos(dos,twoHyphens + boundary + lineEnd);
			doDos(dos,"Content-Disposition: form-data;name=\"uploadedfile\" ;filename=\""
					+ exsistingFileName + "\"" + lineEnd);
			doDos(dos,lineEnd);

			Log.e(Tag, "Headers are written");

			// create a buffer of maximum size

			int bytesAvailable = fileInputStream.available();
			int maxBufferSize = 1024*1024;
			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
			byte[] buffer = new byte[bufferSize];

			// read file and write it into form...

			int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// send multipart form data necesssary after file data...

			doDos(dos,lineEnd);
			doDos(dos,twoHyphens + boundary + twoHyphens + lineEnd);

			// close streams
			Log.e(Tag, "File is written");
			fileInputStream.close();
			dos.flush();

			InputStream is = conn.getInputStream();
			// retrieve the response from server
			int ch;

			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			String s = b.toString();
			resultUrl = s;
			Log.i("Response", s);
			dos.close();

		} catch (MalformedURLException ex) {
			Log.e(Tag, "error: " + ex.getMessage(), ex);
		}
		catch (IOException ioe) {
			Log.e(Tag, "error: " + ioe.getMessage(), ioe);
		}
	}
	private void parseWebResult(){
				
	}
	
	public String getResultURL(){
		return resultUrl;
	}
	private void doDos(DataOutputStream dos, String s) {
		Log.e("DOS", s);
		try {
			dos.writeBytes(s);
		} catch (Exception e) {

		}
	}
	public void run() {
		// TODO Auto-generated method stub
		
	}
}